springboot @Autowired 注入为null 的原因与解决方式

您所在的位置:网站首页 springboot注入为空 解决 springboot @Autowired 注入为null 的原因与解决方式

springboot @Autowired 注入为null 的原因与解决方式

2024-07-13 06:39| 来源: 网络整理| 查看: 265

我遇到的问题是 我是通过反射 new了一个对象 在对象中使用@Autowired,报了空指针,所以只能通过自己写一个工具类获取去bean, 使用工具类方式获取bean如下,不再使用@Autowired注入

private TestMapper testMapper=BeanUtils.getBean(TestMapper.class);

工具类如下

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class BeanUtils implements ApplicationContextAware { protected static ApplicationContext applicationContext ; @Override public void setApplicationContext(ApplicationContext arg0) throws BeansException { if (applicationContext == null) { applicationContext = arg0; } } public static Object getBean(String name) { //name表示其他要注入的注解name名 return applicationContext.getBean(name); } /** * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象 */ public static T getBean(Class clazz) { return applicationContext.getBean(clazz); } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3